<template>
  <ContentWrap :style="`height: ${contentHeight}px;`">
    <div class="mb-10px routeHeader">
      <el-button
        @click="dialogVisible = true"
        type="primary"
        :disabled="formLoading"
        v-if="formType === 'update' && formData.dictDeliveryStatus !== 30"
        v-hasPermi="['produce:logistics-info:receive']"
        >签收</el-button
      >
      <el-button
        @click="printDeliver"
        type="primary"
        :disabled="formLoading"
        v-if="formType === 'view'"
        v-hasPermi="['produce:logistics-info:print']"
        >打印发货单呢</el-button
      >
      <el-button @click="goBack">关闭</el-button>
    </div>
    <el-scrollbar :max-height="`${contentHeight - 73}px`">
      <info ref="infoRef" :detailData="formData" :formType="formType" moduleName="logistics" />
    </el-scrollbar>
  </ContentWrap>
  <!-- 打印 -->
  <div v-show="false" id="printData">
    <print :detailData="formData" />
  </div>
  <!-- 签收弹窗 -->
  <el-dialog title="签收" v-model="dialogVisible" width="40%">
    <el-form ref="receiveRef" label-width="110px" :model="formData" :rules="formRules">
      <el-form-item label="签收附件" prop="receiveFileList">
        <UploadFile
          style="width: auto"
          v-model="formData.receiveFileList"
          :isShowTip="false"
          :limit="1"
          :fileSize="200"
          :fileType="['png', 'jpg', 'pdf']"
          @update:modelValue="uploadReceiveFile"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import * as LogisticsInfoApi from '@/api/produce/productManagement/logisticsInfo'
import { useTagsViewStore } from '@/store/modules/tagsView'
import info from '../components/info.vue'
import print from '../productionShipments/print.vue'

const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const dialogVisible = ref(false)  //签收弹窗显示与否
const formData = ref({
  id: undefined,
  sendNumber: undefined,
  inventoryId: undefined,
  prepareNumber: undefined,
  orderNumber: undefined,
  dictDeliveryType: undefined,
  customerName: undefined,
  productNumber: undefined,
  productName: undefined,
  productStandard: undefined,
  productSize: undefined,
  trainNumber: undefined,
  proportionExpenses: undefined,
  customerAddress: undefined,
  packingAddress: undefined,
  requirements: undefined,
  loadingStartTime: undefined,
  loadingEndTime: undefined,
  licencePlate: undefined,
  vehicleModel: undefined,
  driverName: undefined,
  driverPhone: undefined,
  containerNumber: undefined,
  containerSize: undefined,
  lockNumber: undefined,
  shippingNumber: undefined,
  courierNumber: undefined,
  sendMethod: undefined,
  contactName: undefined,
  contactPhone: undefined,
  sendName: undefined,
  receiveName: undefined,
  creatorName: undefined,
  updaterName: undefined,
  dictDeliveryStatus: undefined,
  trackingNumber: undefined,
  deliveryDate: undefined, //发货时间
  receiveFiles: null, //签收附件
  receiveFileList: [], //签收附件回显
})
const formRules = reactive({
  receiveFileList: [{ required: true, message: '签收附件不能为空', trigger: 'blur' }]
})
const receiveRef = ref()

const contentHeight = ref(0)
const query = useRoute().query as any
const infoRef = ref()

// 关闭
const tagsViewStore = useTagsViewStore()
const { currentRoute, push } = useRouter() // 路由
const goBack = async () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(currentRoute.value)
  push('/produce/produce/productManagement/logisticsInfo')
}

/** 获取数据 */
const getData = async (type: string, id: number) => {
  formType.value = type
  formLoading.value = true
  try {
    formData.value = await LogisticsInfoApi.getLogisticsInfo(id)
    formData.value.receiveFileList = []
  } finally {
    formLoading.value = false
  }
}

// 签收附件上传
const uploadReceiveFile = (data) => {
  if (JSON.parse(data).length) {
    formData.value.receiveFiles = JSON.parse(data).map(item => {
      return {
        fileName: item.name,
        filePath: item.url
      }
    })
  } else {
    formData.value.receiveFiles = null
  }
}

/** 签收 */
const submitForm = async () => {
  // 校验表单
  if (!receiveRef) return
  const valid = await receiveRef.value.validate()
  if (!valid) return
  const data = infoRef.value.formData as LogisticsInfoApi.LogisticsInfoVO
  formLoading.value = true
  try {
    await LogisticsInfoApi.receiveLogisticsInfo(data)
    message.success('签收成功')
    goBack()
  } finally {
    formLoading.value = false
  }
}

// 打印发货单
const printDeliver = () => {
  let winName, head, bdHtml;
  winName = window.open("", "_blank", ""); // 新窗口
  head = '<link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />'
  const tabStyle = `
  <style>
    .title {
      font-size: 22px;
      font-weight: bold;
      text-align: center;
      width: 350px;
      margin: 0 auto;
    }

    .logo {
      float: left;
      width: 200px;
      height: 50px;
    }

    .tab {
      border: 1px solid #e4e7ed;
      text-align: center;
    }

    .d-flex {
      display: flex;
      align-items: center;
    }

    .card {
      height: 50px;
      line-height: 50px;
    }

    .card-confirm {
      height: 100px;
      line-height: 100px;
    }

    .card:not(:last-child),
    .card-confirm:not(:last-child) {
      border-right: 1px solid #e4e7ed;
    }

    .height-100px {
      height: 100px;
    }

    .border-bottom {
      border-bottom: 1px solid #e4e7ed;
    }

    .width-25 {
      width: 25%;
    }

    .width-10 {
      width: 10%;
    }

    .width-20 {
      width: 20%;
    }

    .width-30 {
      width: 30%;
    }
  </style>
  `
  head += tabStyle;
  bdHtml = window.document.querySelector("#printData").innerHTML;
  winName.document.head.innerHTML = head;
  winName.document.body.innerHTML = bdHtml;
  winName.focus(); //聚焦保证页面正常
  setTimeout(() => {
    winName.print();
  }, 500);
}

// 初始化
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 125
  getData(query.type, query.id)
})
</script>
